package com.alipay.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.config.AlipayConfig;
import com.alipay.constant.ProductCode;
import com.alipay.model.request.MiniAppPayRequest;
import com.alipay.model.response.MiniAppPayResponse;
import com.alipay.service.AbstractPayService;

/**
 * @author lwj
 * @create 2025-10-10-23:51
 */
public class MiniAppPayServiceImpl extends AbstractPayService<MiniAppPayRequest, MiniAppPayResponse> {

    public MiniAppPayServiceImpl(AlipayClient alipayClient, AlipayConfig alipayConfig) {
        super(alipayClient, alipayConfig);
    }


    @Override
    protected AlipayRequest createAlipayRequest() {
        return new AlipayTradeAppPayRequest();
    }

    @Override
    protected void fillBizContent(JSONObject bizContent, MiniAppPayRequest request) {
        // 添加小程序授权令牌
        bizContent.put("auth_token", request.getAuthToken());
    }

    @Override
    protected void setRequestParams(AlipayRequest alipayRequest, JSONObject bizContent) {
        // 强转为具体请求类型
        AlipayTradeAppPayRequest appPayRequest = (AlipayTradeAppPayRequest) alipayRequest;
        // 将 JSON 类型转换为 Model 型
        AlipayTradeAppPayModel model = bizContent.toJavaObject(AlipayTradeAppPayModel.class);
        // 设置请求参数
        appPayRequest.setBizModel(model);
    }

    @Override
    protected AlipayResponse executeAlipayRequest(AlipayRequest alipayRequest) throws AlipayApiException {
        // 执行请求
        return alipayClient.sdkExecute((AlipayTradeAppPayRequest) alipayRequest);
    }

    @Override
    protected MiniAppPayResponse handleAlipayResponse(AlipayResponse alipayResponse, MiniAppPayRequest request) {
        MiniAppPayResponse response = new MiniAppPayResponse();
        AlipayTradeAppPayResponse appPayResponse = (AlipayTradeAppPayResponse) alipayResponse;

        // 填充自定义响应对象数据
        return populateResponse(response,appPayResponse);
    }

    @Override
    protected MiniAppPayResponse createEmptyResponse() {
        return new MiniAppPayResponse();
    }

    @Override
    protected String getProductCode() {
        return ProductCode.MINI_APP_PAY;
    }

    @Override
    protected void populateSpecificFields(MiniAppPayResponse response, AlipayResponse alipayResponse) {
        // 强转为小程序支付响应
        AlipayTradeAppPayResponse appPayResponse = (AlipayTradeAppPayResponse) alipayResponse;
        // 设置订单信息
        response.setOrderString(appPayResponse.getBody());
    }
}
